import type {
  EditableFormInstance,
  ProColumns,
  ProFormInstance,
} from "@ant-design/pro-components";
import {
  EditableProTable,
  ProCard,
  ProForm,
  ProFormDependency,
  ProFormField,
  ProFormRadio,
} from "@ant-design/pro-components";
import { Button } from "antd";
import React, { useRef, useState, useEffect } from "react";
import { form } from "../mst/Form";
import { observer } from "mobx-react";
import { useNavigate } from "react-router-dom";
import { getSnapshot } from "mobx-state-tree";

type DataSourceType = {
  id: React.Key;
  title?: string;
  decs?: string;
  state?: string;
  created_at?: string;
  update_at?: string;
  children?: DataSourceType[];
};

let i = 0;

const FormItemSTR = () => {
  const router = useNavigate();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const [position, setPosition] = useState<"top" | "bottom" | "hidden">(
    "bottom"
  );
  const formRef = useRef<ProFormInstance<any>>();
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  const columns: ProColumns<DataSourceType>[] = [
    {
      title: "活动名称",
      dataIndex: "title",
      key: "title",
      formItemProps: () => {
        return {
          rules: [{ required: true, message: "此项为必填项" }],
        };
      },
      width: "30%",
    },
    {
      title: "状态",
      key: "state",
      dataIndex: "state",
      valueType: "select",
      valueEnum: {
        all: { text: "全部", status: "Default" },
        open: {
          text: "未解决",
          status: "Error",
        },
        closed: {
          text: "已解决",
          status: "Success",
        },
      },
    },
    {
      title: "描述",
      dataIndex: "decs",
      key: "desc",
    },
    {
      title: "活动时间",
      dataIndex: "created_at",
      valueType: "date",
      key: "date",
    },
    {
      title: "操作",
      valueType: "option",
      key: "option",
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            const tableDataSource = formRef.current?.getFieldValue(
              "table"
            ) as DataSourceType[];
            formRef.current?.setFieldsValue({
              table: tableDataSource.filter((item) => item.id !== record.id),
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  //点击提交
  const DoSubmit = () => {
    const newData = formRef.current?.getFieldsValue().table;
    // console.log(newData);
    form.changeProps(newData);
    console.log("当前mst里的数据", JSON.parse(getSnapshot(form).data));
  };

  let defaultData = JSON.parse(form.data);

  return (
    <ProForm<{
      table: DataSourceType[];
    }>
      formRef={formRef}
      initialValues={{
        table: defaultData,
      }}
      validateTrigger="onBlur"
      // submitter={false}
      submitter={{
        // 配置按钮文本
        searchConfig: {
          resetText: "重置",
          submitText: "提交",
        },
        // 配置按钮的属性
        resetButtonProps: {
          style: {
            // 隐藏重置按钮
            display: "none",
          },
        },
        submitButtonProps: {},

        // 完全自定义整个区域
        render: (props, doms) => {
          // console.log(props);
          return [
            <Button key="rest" onClick={() => props.form?.resetFields()}>
              重置
            </Button>,
            <Button key="submit" onClick={() => DoSubmit()}>
              提交
            </Button>,
            <Button onClick={() => router("/demo")}>去demo</Button>,
          ];
        },
      }}
    >
      <EditableProTable<DataSourceType>
        rowKey="id"
        scroll={{
          x: 960,
        }}
        editableFormRef={editorFormRef}
        headerTitle="可编辑表格"
        maxLength={5}
        name="table"
        recordCreatorProps={
          position !== "hidden"
            ? {
                position: position as "top",
                record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
              }
            : false
        }
        toolBarRender={() => [
          <ProFormRadio.Group
            key="render"
            fieldProps={{
              style: {
                marginBlockEnd: 0,
              },
              value: position,
              onChange: (e) => setPosition(e.target.value),
            }}
            options={[
              {
                label: "添加到顶部",
                value: "top",
              },
              {
                label: "添加到底部",
                value: "bottom",
              },
              {
                label: "隐藏",
                value: "hidden",
              },
            ]}
          />,
          <Button
            type="text"
            key="rows"
            onClick={() => {
              const rows = editorFormRef.current?.getRowsData?.();
              console.log(rows);
            }}
          >
            获取 table 的数据
          </Button>,
        ]}
        columns={columns}
        editable={{
          type: "multiple",
          editableKeys,
          onChange: setEditableRowKeys,
          actionRender: (row, config, defaultDom) => {
            return [
              defaultDom.save,
              defaultDom.delete || defaultDom.cancel,
              <a
                key="set"
                onClick={() => {
                  i++;
                  editorFormRef.current?.setRowData?.(config.index!, {
                    title: "动态设置的title" + i,
                  });
                }}
              >
                动态设置此行
              </a>,
            ];
          },
        }}
      />
      <ProForm.Item>
        <ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
          <ProFormDependency name={["table"]}>
            {({ table }) => {
              return (
                <ProFormField
                  ignoreFormItem
                  fieldProps={{
                    style: {
                      width: "100%",
                    },
                  }}
                  mode="read"
                  valueType="jsonCode"
                  text={JSON.stringify(table)}
                />
              );
            }}
          </ProFormDependency>
        </ProCard>
      </ProForm.Item>
    </ProForm>
  );
};

export default observer(FormItemSTR);
